#!/usr/bin/python
#Leon Teale
#http://secheads.co.uk
#http://batserver.co.uk

"""
Pre-requisites: libnmap
-----------------------
You can install libnmap via pip:

pip install libnmap

or via git:

$ git clone https://github.com/savon-noir/python-libnmap.git
$ cd python-libnmap
$ python setup.py install
-----------------------

  USAGE : python Parser_nmap.py file1.xml file2.xml ...
"""
import sys
from libnmap.parser import NmapParser

def Parse(filename, output):
    nmap_report = NmapParser.parse_fromfile(filename)
    print "Nmap scan summary: {0}".format(nmap_report.summary)
    output.write("TCP\n")
    output.write("Machine,Open,Filtered,Closed,OS detection guess,ICMP response\n")
    for host in nmap_report.hosts:
        port_tcp_open=0
        port_tcp_closed=0
        output.write(str(host.address)+",")
        for port in host.get_ports():
            a,b = port
            if host.get_service(a,b).open():
                port_tcp_open+=1
            else:
                port_tcp_closed+=1
        port_tcp_filtered = int(str(host.extraports_state['count']).split(":")[1].split("'")[1])
        output.write(str(port_tcp_open)+","+str(port_tcp_filtered)+","+str(port_tcp_closed)+",")
        if host.os_fingerprinted:
            for a in host.os_match_probabilities():
                c = str(a).split(":")
                output.write(c[0].strip("\r\n") + "("+c[1].split(" ")[1].strip("\r\n")+"%) / ")
            output.write(",")
        else:
            output.write("Unknown,")

        output.write(host.status)
        output.write("\r\n")


for file in sys.argv[1:]:
    if file == "-h":
        print " USAGE : python Parser_nmap.py file1.xml file2.xml\n"
        break
    output_filename = str(file).split(".")[0]+"_output.csv"
    f = open(output_filename,"w")
    Parse(file,f)
    print "[+] "+file + " parsed and CSV generated at "+output_filename




